package com.gxuwz.stats.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.gxuwz.stats.config.DateConfig;
import com.gxuwz.stats.entity.AcademicWork;
import com.gxuwz.stats.entity.ScientificActivity;
import com.gxuwz.stats.entity.User;
import com.gxuwz.stats.security.jwt.JwtTokenUtil;
import com.gxuwz.stats.service.ScientificActivityService;
import com.gxuwz.stats.service.ScientificActivityService;
import com.gxuwz.stats.service.UserService;
import com.gxuwz.stats.utils.ExcelExportUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/scientificActivity")
public class ScientificActivityController {

    @Autowired
    private ScientificActivityService scientificActivityService;
    @Autowired
    private UserService userService;

    /**
     * 获取用户列表
     * @param params 请求参数
     * @param currentPage 当前页码
     * @param pageSize    每页大小
     * @return
     */
    @GetMapping("/scientificActivityList")
    public ResponseEntity<Map<String, Object>> scientificActivityList(
            @RequestParam Map<String, String> params,
            @RequestParam(defaultValue = "1") int currentPage,
            @RequestParam(defaultValue = "10") int pageSize) {
        try {
            // 创建 MyBatis Plus 的 Page 对象进行分页查询
            IPage<ScientificActivity> page = new Page<>(currentPage, pageSize);
            QueryWrapper<ScientificActivity> queryWrapper = new QueryWrapper<>();

            // 根据用户名获取用户ID列表并加入查询条件
            if (params.containsKey("username") && !params.get("username").trim().isEmpty()) {
                List<String> userIds = userService.getUserIdsByKeyword(params.get("username"));
                if (!userIds.isEmpty()) {
                    queryWrapper.in("user_id", userIds);
                } else {
                    // 如果没有找到对应的userId，则返回空结果
                    queryWrapper.eq("1", "0");
                }
            }

            // 模糊查询条件 - 项目名称
            if (params.containsKey("scientificWorkName") && params.get("scientificWorkName") != null && !params.get("scientificWorkName").isEmpty()) {
                queryWrapper.like("scientific_work_name", params.get("scientificWorkName"));
            }

            // 模糊查询条件 - 项目级别
            if (params.containsKey("scientificCategory") && params.get("scientificCategory") != null && !params.get("scientificCategory").isEmpty()) {
                queryWrapper.like("scientific_category", params.get("scientificCategory"));
            }

            // 模糊查询条件 - 获得时间
            if (params.containsKey("scientificYear") && params.get("scientificYear") != null && !params.get("scientificYear").isEmpty()) {
                queryWrapper.apply("YEAR(scientific_year) = {0}", params.get("scientificYear"));
            }

            // 模糊查询条件 - 审核状态
            if (params.containsKey("scientificReviewStatus") && params.get("scientificReviewStatus")!= null &&!params.get("scientificReviewStatus").isEmpty()) {
                queryWrapper.eq("scientific_review_status", params.get("scientificReviewStatus"));
            }

            // 模糊查询条件 - 提交状态
            if (params.containsKey("scientificStatus") && params.get("scientificStatus")!= null &&!params.get("scientificStatus").isEmpty()) {
                queryWrapper.eq("scientific_status", params.get("scientificStatus"));
            }

            // 调用 service 层的分页查询方法
            IPage<ScientificActivity> resultPage = scientificActivityService.getSAListWithUserInfo(page, queryWrapper);

            // 构造返回结果
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "查询成功");
            response.put("data", resultPage.getRecords()); // 当前页数据
            response.put("total", resultPage.getTotal()); // 总记录数
            response.put("currentPage", resultPage.getCurrent()); // 当前页码
            response.put("pageSize", resultPage.getSize()); // 每页大小
            response.put("totalPages", resultPage.getPages()); // 总页数

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            e.printStackTrace();
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "查询失败: " + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResponse);
        }
    }

    /**
     * 新增
     */
    @PostMapping("/addScientificActivity")
    public ResponseEntity<Map<String, Object>> addScientificActivity(@RequestBody ScientificActivity scientificActivity) {
        // 创建响应 Map
        Map<String, Object> response = new HashMap<>();

        // 1. 验证 username 是否存在
        String username = scientificActivity.getUsername();
        if (username == null || username.isEmpty()) {
            response.put("code", 400);
            response.put("msg", "用户名不能为空");
            return ResponseEntity.badRequest().body(response);
        }

        // 2. 根据 username 查询 user_id
        String userId = userService.getUserIdByUsername(username);
        if (userId == null) {
            response.put("code", 400);
            response.put("msg", "用户不存在");
            return ResponseEntity.badRequest().body(response);
        }
        System.out.println("获取到的 user_id：" + userId);

        // 3. 设置 user_id 并保存
        scientificActivity.setUserId(userId);

        // 1. 自动计算分值
        int baseScore = scientificActivityService.getScoreByType(scientificActivity.getScientificCategory());
        scientificActivity.setScientificScore(baseScore);

        // 2. 计算总分值并保存到ScientificActivitySum表
        scientificActivityService.calculateTotalScore(scientificActivity);

        scientificActivity.setScientificSubmissionTime(LocalDateTime.now());
        // 设置默认值
        scientificActivity.setScientificStatus("已提交");
        scientificActivity.setScientificReviewStatus("未审核");

        try {
            // 保存到数据库
            scientificActivityService.save(scientificActivity);

            String year = null;
            if (scientificActivity.getScientificYear() != null) {
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                    year = sdf.format(scientificActivity.getScientificYear());
                } catch (Exception e) {
                    year = scientificActivity.getScientificYear().substring(0, 4);
                }
            }
            if (year != null) {
                scientificActivityService.updateTotalWorkActivityScore(userId, year);
            }

            // 返回成功响应
            response.put("code", 200);
            response.put("msg", "新增成功");
            return ResponseEntity.status(HttpStatus.CREATED).body(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "服务器内部错误");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    /**
     * 删除
     */
    @DeleteMapping("/deleteScientificActivity")
    public ResponseEntity<Map<String, Object>> deleteScientificActivity(@RequestBody List<Long> scientificActivityIds) {
        // 1. 查出所有要删的数据
        List<ScientificActivity> toDelete = scientificActivityService.listByIds(scientificActivityIds);

// 2. 记录所有受影响的 userId+year 组合
        Set<String> userYearSet = new HashSet<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
        for (ScientificActivity sa : toDelete) {
            if (sa.getUserId() != null && sa.getScientificYear() != null) {
                String year;
                try {
                    year = sdf.format(sdf.parse(sa.getScientificYear()));
                } catch (Exception e) {
                    year = sa.getScientificYear().substring(0, 4);
                }
                userYearSet.add(sa.getUserId() + "#" + year);
            }
        }

// 3. 删除
        scientificActivityService.removeByIds(scientificActivityIds);

// 4. 删除后，逐个更新 TotalWork
        for (String userYear : userYearSet) {
            String[] arr = userYear.split("#");
            String userId = arr[0];
            String year = arr[1];
            scientificActivityService.updateTotalWorkActivityScore(userId, year);
        }
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "删除成功");
        return ResponseEntity.ok(response);
    }

    /**
     * 修改
     */
    @PutMapping("/editScientificActivity")
    public ResponseEntity<Map<String, Object>> editScientificActivity(@RequestBody ScientificActivity scientificActivity) {
        // 1. 获取前端传递的用户名
        String username = scientificActivity.getUsername();
//        System.out.println("shdjs="+username);
        if (username != null && !username.isEmpty()) {
            // 2. 查询用户信息
            User user = userService.getOne(new QueryWrapper<User>().eq("username", username));
//            System.out.println("user="+user);
            if (user == null) {
                Map<String, Object> response = new HashMap<>();
                response.put("code", 400);
                response.put("msg", "用户不存在");
                return ResponseEntity.badRequest().body(response);
            }
            // 3. 设置 userId
            scientificActivity.setUserId(user.getUserId());
        }
        // 1. 自动计算分值
        int baseScore = scientificActivityService.getScoreByType(scientificActivity.getScientificCategory());
        scientificActivity.setScientificScore(baseScore);

        // 2. 计算总分值并保存到ScientificActivitySum表
        scientificActivityService.calculateTotalScore(scientificActivity);

        scientificActivityService.updateById(scientificActivity);

        String year = null;
        if (scientificActivity.getScientificYear() != null) {

            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy");
                year = sdf.format(scientificActivity.getScientificYear());
            } catch (Exception e) {
                year = scientificActivity.getScientificYear().substring(0, 4);
            }

        }
        if (year != null) {
            scientificActivityService.updateTotalWorkActivityScore(scientificActivity.getUserId(), year);
        }

        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("msg", "修改成功");
        return ResponseEntity.ok(response);
    }

    @PostMapping("/reviewScientificActivity")
    public ResponseEntity<Map<String, Object>> reviewScientificActivity(@RequestBody Map<String, Object> params) {
        Map<String, Object> response = new HashMap<>();
        try {
            Long scientificId = Long.valueOf(params.get("scientificId").toString());
            String reviewStatus = params.get("reviewStatus").toString(); // 审核通过/审核不通过
            String reviewResult = params.get("reviewResult") != null ? params.get("reviewResult").toString() : "";

            ScientificActivity scientificActivity = scientificActivityService.getById(scientificId);
            if (scientificActivity == null) {
                response.put("code", 404);
                response.put("msg", "数据不存在");
                return ResponseEntity.ok(response);
            }

            // 设置审核状态、审核时间、审核说明
            scientificActivity.setScientificReviewStatus(reviewStatus);
            scientificActivity.setScientificReviewTime(java.time.LocalDateTime.now());
            scientificActivity.setScientificReviewResult(reviewResult);

            if ("审核通过".equals(reviewStatus)) {
                scientificActivity.setScientificReviewResult(null); // 审核通过时清空说明
            }
            if ("审核不通过".equals(reviewStatus)) {
                scientificActivity.setScientificStatus("未提交");
            }

            scientificActivityService.updateById(scientificActivity);

            response.put("code", 200);
            response.put("msg", "审核成功");
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            response.put("code", 500);
            response.put("msg", "审核失败：" + e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
        }
    }

    @GetMapping("/export")
    public void exportScientificActivity(
            @RequestParam(value = "year", required = false) String year,
            HttpServletResponse response) throws Exception {


        // 3. 查询 ScientificActivity（可按年份筛选）
        QueryWrapper<ScientificActivity> queryWrapper = new QueryWrapper<>();

        if (year != null && !year.isEmpty()) {
            queryWrapper.like("scientific_year", year.substring(0, 4)); // 替换为你的年份字段
        }

        // 只导出审核通过的数据
        queryWrapper.eq("scientific_status", "已提交");

        List<ScientificActivity> list = scientificActivityService.list(queryWrapper);

        // 4. 查询所有用户，构建 userId -> username 映射
        List<User> userList = userService.list();
        Map<String, String> userIdNameMap = userList.stream()
                .collect(Collectors.toMap(User::getUserId, User::getUsername, (a, b) -> a));
        for (ScientificActivity sa : list) {
            sa.setUsername(userIdNameMap.getOrDefault(sa.getUserId(), ""));
        }

        // 5. 给每条数据加序号（如有 rowNum 字段）
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setRowNum(i + 1); // 如果有 rowNum 字段
        }

        // 6. 生成文件名
        String now = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        String fileName = "科技活动-"  + now + ".xlsx";

        // 7. 导出
        ExcelExportUtil.export(response, list, ScientificActivity.class, "科技活动", fileName);
    }


}
